package com.business_clean.ui.fragment.addproject;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.Observer;

import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.GlideUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.data.initconfig.BankInfoEntity;
import com.business_clean.data.mode.members.BankEntity;
import com.business_clean.data.mode.members.IDCardMemberEntity;
import com.business_clean.data.mode.members.MembersDetailEntity;
import com.business_clean.data.mode.members.OCRBankInfoEntity;
import com.business_clean.databinding.FragmentBankCardBinding;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.hgj.mvvmhelper.ext.LogExtKt;

public class BankCardFragment extends BaseFragment<ProjectMembersViewModel, FragmentBankCardBinding> {

    private String bank_code;

    private String[] strings = {"拍照", "相册"};

    private String bank_card_front = "";

    private String uuid = "";

    private int type = 0;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        getMDatabind().withBankNo.setInputNumber();
    }

    @Override
    public void lazyLoadData() {
        if (getArguments() != null) {//说明已经存在了
            uuid = getArguments().getString("uuid");
            type = getArguments().getInt("type");
            String application_no = getArguments().getString("application_no");

            HashMap<String, String> hashMap = new HashMap<>();
            if (!TextUtils.isEmpty(uuid)) {
                hashMap.put("uuid", uuid);
            }
            if (!TextUtils.isEmpty(application_no)) {
                hashMap.put("application_no", application_no);
            }
            hashMap.put("is_bank", "1");
            //1是草稿编辑  2是草稿新建 3是档案详情
            if (type == 3) {
                mViewModel.requestStaffDetail(hashMap);//真正的详情
            } else {
                mViewModel.requestMembersDetail(hashMap);//草稿的详情，还没真的成为员工
            }
        }
    }


    @Override
    public void initObserver() {
        App.appViewModelInstance.getCreateUuid().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                uuid = s;
            }
        });
    }

    @Override
    public void onBindViewClick() {
        getMDatabind().ivCard1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSelectedPic();
            }
        });
        //选择银行
        getMDatabind().withBankH.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AddProjectActivity.initDataEntity != null && AddProjectActivity.initDataEntity.getBank_list().size() > 0) {
                    CommonUtils.showDialogWheelSingleList(getMActivity(), "请选择银行",
                            getArrayListString(AddProjectActivity.initDataEntity.getBank_list()), getMDatabind().withBankH.getTvRight(), new OnDialogSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    bank_code = AddProjectActivity.initDataEntity.getBank_list().get(position).getCode();
                                    getMDatabind().withBankH.setTvRightText(text);
                                }
                            });
                }
            }
        });
        getMDatabind().bottom.butBottomButLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.appViewModelInstance.getProjectLastPersonnel().setValue(1);
            }
        });
        getMDatabind().bottom.butBottomButNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("请选择".equals(getMDatabind().withBankH.getTvRight())
                        && TextUtils.isEmpty(getMDatabind().withBankName.getInputText())
                        && TextUtils.isEmpty(getMDatabind().withBankNo.getInputText())) {
                    App.appViewModelInstance.getProjectPersonnel().setValue(3);
                    return;
                }
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("op_type", "bank");
                hashMap.put("uuid", uuid);
                if (!TextUtils.isEmpty(bank_card_front)) {
                    hashMap.put("bank_card_front", "" + bank_card_front);
                }
                hashMap.put("bank_no", "" + getMDatabind().withBankNo.getInputText());
                hashMap.put("bank_code", "" + bank_code);
                hashMap.put("bank", "" + getMDatabind().withBankH.getTvRight());
                hashMap.put("bank_name", "" + getMDatabind().withBankName.getInputText());
                mViewModel.requestUpdateMembers(hashMap, AddProjectActivity.ID_BANK, type);
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getUpdateBankStatus().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                App.appViewModelInstance.getProjectPersonnel().setValue(3);
            }
        });

        mViewModel.getMembersDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                uuid = membersDetailEntity.getUuid();
                fillData(membersDetailEntity.getBank());
            }
        });

        mViewModel.getOcrBankInfo().observe(this, new Observer<OCRBankInfoEntity>() {
            @Override
            public void onChanged(OCRBankInfoEntity ocrBankInfoEntity) {
                fillOCRBankInfo(ocrBankInfoEntity);
            }
        });
    }

    private void fillOCRBankInfo(OCRBankInfoEntity ocrBankInfoEntity) {
        if (ocrBankInfoEntity != null) {
            getMDatabind().withBankNo.setInputText(ocrBankInfoEntity.getBank_card_number());
            getMDatabind().withBankH.setTvRightText(ocrBankInfoEntity.getBank_name());
            bank_code = ocrBankInfoEntity.getBank_code();
        }
    }

    private void fillData(BankEntity bank) {
        if (bank != null) {
            if (bank.getPic_list().size() > 0) {
                bank_card_front = bank.getPic_list().get(0).getSource_url();
                if (!TextUtils.isEmpty(bank_card_front)) {
                    GlideUtil.loadPic(getActivity(), bank_card_front, getMDatabind().ivCard1);
                }
            }
            bank_code = bank.getBank_code();
            getMDatabind().withBankNo.setInputText(bank.getBank_no());
            getMDatabind().withBankH.setTvRightText(bank.getBank());
            getMDatabind().withBankName.setTvRightText(bank.getBank_name());
        }
    }

    /**
     * 打开相册，让选择
     */
    private void showBottomSelectedPic() {
        CommonUtils.showBottomListWith(getActivity(), 20, "", strings, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                switch (position) {
                    case 0:
                        ChoosePicUtil.openCameraTake(getMActivity(), new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                uploadPic(result);
                                GlideUtil.loadPicRound(getMActivity(), result.get(0).getCompressPath(), getMDatabind().ivCard1, 0);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        break;
                    case 1:
                        ChoosePicUtil.openAlbum(getMActivity(), 1, new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                uploadPic(result);
                                GlideUtil.loadPicRound(getMActivity(), result.get(0).getCompressPath(), getMDatabind().ivCard1, 0);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        break;
                }
            }
        });
    }


    /**
     * 上传图片 区分正反
     */
    private void uploadPic(ArrayList<LocalMedia> result) {
        LoadingDialogExtKt.showLoadingExt(this, "上传中");
        ArrayList<String> strings1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            strings1.add(result.get(i).isCompressed() ? result.get(i).getCompressPath() : result.get(i).getRealPath());
        }
        UploadFileHelper.getInstance().uploadFiles(getActivity(), strings1, UploadFileHelper.PATH_HEADER_PERSONNEL, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String response) {
                LogExtKt.logE("最后回调到的图片---> " + response, "");
                bank_card_front = response;
                mViewModel.requestBankInfo(response);
                LoadingDialogExtKt.dismissLoadingExt(BankCardFragment.this);
            }

            @Override
            public void onUploadFailed(String error) {
                ToastUtil.show("上传失败");
                LoadingDialogExtKt.dismissLoadingExt(BankCardFragment.this);
            }

            @Override
            public void onUploadProgress(int progress) {

            }


        });
    }


    private ArrayList<String> getArrayListString(List<BankInfoEntity> list) {
        ArrayList<String> names = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            names.add(list.get(i).getName());
        }
        return names;
    }

}
